import React, { useState, useEffect, useRef } from 'react';

// 定义Unity实例的类型
interface UnityInstance {
  SetFullscreen: (mode: number) => void;
  SendMessage: (objectName: string, methodName: string, parameter?: any) => void;
  // 可以根据需要添加更多Unity实例方法
}

const UnityWebGLPlayer: React.FC = () => {
  const [progress, setProgress] = useState(0);
  const [isLoaded, setIsLoaded] = useState(false);
  const [banners, setBanners] = useState<Array<{msg: string, type: string}>>([]);
  
  const unityInstanceRef = useRef<UnityInstance | null>(null);
  const canvasRef = useRef<HTMLCanvasElement>(null);
  const containerRef = useRef<HTMLDivElement>(null);

  // 显示提示信息
  const unityShowBanner = (msg: string, type: string = 'info') => {
    setBanners(prev => [...prev, { msg, type }]);
    
    if (type !== 'error') {
      setTimeout(() => {
        setBanners(prev => prev.filter(banner => !(banner.msg === msg && banner.type === type)));
      }, 5000);
    }
  };

  // 处理全屏切换
  const handleFullscreen = () => {
    if (unityInstanceRef.current) {
      unityInstanceRef.current.SetFullscreen(1);
    }
  };

  // 处理获取所有物体
  const handleGetAllObjects = () => {
    if (unityInstanceRef.current) {
      unityInstanceRef.current.SendMessage("ObjectManager", "GetAllObjectNames");
    }
  };
  const handleChangeCamera = () => {
    (window as any).setCameraTransform({ x: 6.61, y: 2.36, z: -15 }, { x: 0, y: 0, z: 0 }, 60);
  }
  // region callback-unity
  
  useEffect(() => {
    // 定义回调函数并挂载到window对象
    (window as any).receiveObjectNames = (objectNamesJson: string) => {
      try {
        const wrapper = JSON.parse(objectNamesJson);
        // 注意原代码中的拼写错误 obejcts -> objects
        const objects = wrapper.objects || [];

        console.log(objects)
        
        // 更新组件状态
        // setObjectNames(objects);
        
        console.log('Received objects from Unity:', objects);
      } catch (error) {
        console.error('Error parsing object names:', error);
      }
    };

    (window as any).setCameraTransform = (position: { x: any; y: any; z: any; }, rotation: { x: any; y: any; z: any; }, fieldOfView: number) => {
        const jsonParams = JSON.stringify({
          position: {
            x: position.x,
            y: position.y,
            z: position.z,
          },
          rotation: {
            x: rotation.x,
            y: rotation.y,
            z: rotation.z,
          },
          fieldOfView: fieldOfView,
        });
        if(unityInstanceRef.current) {
            unityInstanceRef.current.SendMessage("Main Camera", "JS_SetCameraTransform", jsonParams);
        }
      }
    
    // 组件卸载时清理全局函数，避免内存泄漏
    return () => {
      delete (window as any).receiveObjectNames;
    };
  }, []); // 空依赖数组确保只在组件挂载时执行一次

  // 加载Unity
  useEffect(() => {
    // 检测是否是移动设备
    const isMobile = /iPhone|iPad|iPod|Android/i.test(navigator.userAgent);
    
    // 移动设备添加视口元标签
    if (isMobile) {
      const meta = document.createElement('meta');
      meta.name = 'viewport';
      meta.content = 'width=device-width, height=device-height, initial-scale=1.0, user-scalable=no, shrink-to-fit=yes';
      document.head.appendChild(meta);
    }

    // 配置Unity
    const buildUrl = "Build";
    
    const loaderUrl = `${buildUrl}/072552122.loader.js`;
    const config = {
      dataUrl: `${buildUrl}/072552122.data.gz`,
      frameworkUrl: `${buildUrl}/072552122.framework.js.gz`,
      codeUrl: `${buildUrl}/072552122.wasm.gz`,
      streamingAssetsUrl: "StreamingAssets",
      companyName: "DefaultCompany",
      productName: "3d-built-in",
      productVersion: "0.1",
      showBanner: unityShowBanner,
      // 移动设备可以降低分辨率以提高性能
      ...(isMobile && { devicePixelRatio: 1 })
    };

    // 动态加载Unity loader脚本
    const script = document.createElement("script");
    script.src = loaderUrl;
    
    script.onload = () => {
      // @ts-ignore: Unity的全局函数
      if (window.createUnityInstance && canvasRef.current) {
        // @ts-ignore: Unity的全局函数
        window.createUnityInstance(canvasRef.current, config, (progress: number) => {
          setProgress(progress * 100);
        }).then((instance: UnityInstance) => {
          unityInstanceRef.current = instance;
          setIsLoaded(true);
        }).catch((message: string) => {
          alert(message);
        });
      }
    };

    document.body.appendChild(script);

    // 清理函数
    return () => {
      document.body.removeChild(script);
      // 移除添加的meta标签
      if (isMobile) {
        const meta = document.querySelector('meta[name="viewport"]');
        if (meta) document.head.removeChild(meta);
      }
    };
  }, []);

  return (
    <div 
      ref={containerRef} 
      className={`unity-container ${/iPhone|iPad|iPod|Android/i.test(navigator.userAgent) ? 'unity-mobile' : 'unity-desktop'}`}
      style={{
        width: '100%',
        height: '100%',
        position: 'relative'
      }}
    >
      <canvas 
        ref={canvasRef} 
        id="unity-canvas" 
        tabIndex={-1}
        className={/iPhone|iPad|iPod|Android/i.test(navigator.userAgent) ? 'unity-mobile' : ''}
        style={{
          width: /iPhone|iPad|iPod|Android/i.test(navigator.userAgent) ? '100%' : '960px',
          height: /iPhone|iPad|iPod|Android/i.test(navigator.userAgent) ? '100%' : '600px',
          display: isLoaded ? 'block' : 'none'
        }}
      />
      
      {/* 加载进度条 */}
      <div 
        id="unity-loading-bar" 
        style={{
          display: isLoaded ? 'none' : 'block',
          position: 'absolute',
          top: '50%',
          left: '50%',
          transform: 'translate(-50%, -50%)',
          textAlign: 'center'
        }}
      >
        <div id="unity-logo" style={{ marginBottom: '10px' }}>
          {/* 可以在这里添加Unity logo */}
          <div style={{ fontSize: '24px', fontWeight: 'bold' }}>Unity WebGL</div>
        </div>
        <div 
          id="unity-progress-bar-empty" 
          style={{
            width: '200px',
            height: '20px',
            backgroundColor: '#eee',
            margin: '0 auto'
          }}
        >
          <div 
            id="unity-progress-bar-full" 
            style={{
              height: '100%',
              backgroundColor: '#4CAF50',
              width: `${progress}%`,
              transition: 'width 0.1s ease-in-out'
            }}
          />
        </div>
      </div>
      
      {/* 警告/错误信息 */}
      <div 
        id="unity-warning" 
        style={{
          position: 'absolute',
          top: '10px',
          left: '10px',
          right: '10px',
          zIndex: 100
        }}
      >
        {banners.map((banner, index) => (
          <div 
            key={index}
            style={{
              padding: '10px',
              marginBottom: '5px',
              backgroundColor: banner.type === 'error' ? 'red' : 
                             banner.type === 'warning' ? 'yellow' : '#333',
              color: banner.type === 'warning' ? '#000' : 'white'
            }}
          >
            {banner.msg}
          </div>
        ))}
      </div>
      
      {/* 底部工具栏 */}
      <div 
        id="unity-footer" 
        style={{
          position: 'absolute',
          bottom: '0',
          left: '0',
          right: '0',
          height: '30px',
          display: 'flex',
          alignItems: 'center',
          justifyContent: 'space-between',
          padding: '0 10px',
          backgroundColor: 'rgba(0, 0, 0, 0.5)',
          color: 'white'
        }}
      >
        <div id="unity-webgl-logo" style={{ fontSize: '12px' }}>WebGL</div>
        <button 
          id="unity-fullscreen-button"
          onClick={handleFullscreen}
          style={{
            cursor: 'pointer',
            backgroundColor: 'transparent',
            border: 'none',
            color: 'white',
            fontSize: '14px'
          }}
        >
          全屏
        </button>
        <button 
          id="unity-getallobject"
          onClick={handleGetAllObjects}
          style={{
            cursor: 'pointer',
            backgroundColor: 'transparent',
            border: 'none',
            color: 'white',
            fontSize: '14px'
          }}
        >
          获取所有物体
        </button>
        <button 
          id="unity-getallobject"
          onClick={handleChangeCamera}
          style={{
            cursor: 'pointer',
            backgroundColor: 'transparent',
            border: 'none',
            color: 'white',
            fontSize: '14px'
          }}
        >
          换视角
        </button>
        <div id="unity-build-title">3d-built-in</div>
      </div>
    </div>
  );
};

export default UnityWebGLPlayer;
